<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>购物车</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <style>
        .thColor {
            background-color: lightgray;
        }

        h2 {
            width: 50%;
            margin-left: 25%;
        }
    </style>
</head>
<body>
    <div id="app">
        <table border="1px" width="50%" cellspacing="0" align="center">
            <tr :class="{thColor:ThColor}">
                <th></th>
                <th>书籍名称</th>
                <th>出版日</th>
                <th>价格</th>
                <th>购买数量</th>
                <th>操作</th>
            </tr>
            <tr v-for="(element,index) in books" align="center">
                <td>{{index + 1}}</td>
                <td>{{element.name}}</td>
                <td>{{element.date}}</td>
                <td>¥ {{element.price}}</td>
                <td>
                    <input :disabled="element.count<=1" type="button" value="-" @click="deleteCount(index)">
                    {{element.count}}
                    <input type="button" value="+" @click="addCount(index)">
                </td>
                <td><input type="button" value="移除" @click="removeBook(index)"></td>
            </tr>
        </table>
        <h2>总价格：¥ {{total}}</h2>
    </div>
</body>
<script>
    var app = new Vue({
        el:"#app",
        data:{
            books:[
                {"name":"《java编程思想》","date":"2020-9","price":98.00,"count":1},
                {"name":"《数据分析与数据原理》","date":"2019-2","price":39.00,"count":1},
                {"name":"《Hadoop权威指南》","date":"2020-10","price":59.00,"count":1},
                {"name":"《代码大全》","date":"2018-8","price":128.00,"count":1}
            ],
            total:0,
            ThColor:true
        },
        methods:{
            // 增加书籍数量
            addCount(index){
                var book = this.books[index]
                book.count += 1
                this.total += book.price
            },
            // 减少书籍数量
            deleteCount(index){
                var book = this.books[index]
                book.count -= 1
                this.total -= book.price
            },
            // 移除书籍
            removeBook(index){
                if(confirm("确定移除?")){
                    var book = this.books[index]
                    this.total -= (book.count * book.price)
                    this.books.splice(index,1)
                }
            }
        },
        // 实例创建后计算总价格
        created(){
            for (var i = 0; i < this.books.length; i++) {
                this.total += this.books[i].count * this.books[i].price
            } 
        }
    })
</script>
</html>